import { useState, useCallback } from 'react';
import { message } from 'antd';
import { menuApi, type MenuListParams, type CreateMenuRequest, type UpdateMenuRequest } from '../../services/cloud/api/menuApi';
import type { Menu } from '../../types/rbac';
import { useAsyncState } from '../common/useErrorHandler';

// 菜单表单数据类型
export interface MenuFormData {
  id?: string;
  code: string;
  name: string;
  permissions?: string;
  parentId?: string;
  type: number;
  icon?: string;
  path?: string;
  status?: number;
  description?: string;
  sort?: number;
}

// 菜单搜索参数
export interface MenuSearchParams extends Omit<MenuListParams, 'current' | 'size'> {
  keyword?: string;
}

/**
 * 菜单管理hooks
 */
export const useMenus = () => {
  const { executeAsync, hasAnyLoading } = useAsyncState();
  
  // 菜单数据状态
  const [menus, setMenus] = useState<Menu[]>([]);
  const [menuTree, setMenuTree] = useState<Menu[]>([]);
  const [searchParams, setSearchParams] = useState<MenuSearchParams>({});
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);

  // 根据关键词筛选菜单（前端筛选，用于搜索功能）
  const filterMenusByKeyword = useCallback((menus: Menu[], keyword: string): Menu[] => {
    const filtered: Menu[] = [];
    
    for (const menu of menus) {
      const matchesKeyword = menu.name.toLowerCase().includes(keyword.toLowerCase()) ||
                           menu.code.toLowerCase().includes(keyword.toLowerCase());
      
      let filteredChildren: Menu[] = [];
      if (menu.children) {
        filteredChildren = filterMenusByKeyword(menu.children, keyword);
      }
      
      if (matchesKeyword || filteredChildren.length > 0) {
        filtered.push({
          ...menu,
          children: filteredChildren.length > 0 ? filteredChildren : menu.children
        });
      }
    }
    
    return filtered;
  }, []);

  // 获取菜单树形数据
  const fetchMenus = useCallback(async (params?: MenuSearchParams) => {
    return executeAsync('fetchMenus', async () => {
      try {
        // 调用真实的菜单树形接口，不传递status参数以获取所有状态的菜单
        const treeData = await menuApi.getMenuTree(params?.type);
        
        // 如果有关键词搜索，需要在前端进行过滤（因为getMenuTree接口不支持关键词参数）
        let filteredData = treeData;
        
        if (params?.keyword) {
          filteredData = filterMenusByKeyword(treeData, params.keyword);
        }
        
        setMenus(filteredData);
        setMenuTree(treeData); // 保持完整的树形数据用于父菜单选择
        
        // 默认展开第一级菜单
        const firstLevelKeys = filteredData.map(item => item.id);
        setExpandedKeys(firstLevelKeys);
        
        return filteredData;
      } catch (error: any) {
        // 根据错误类型显示不同的错误信息
        if (error?.response?.status === 401) {
          throw new Error('登录已过期，请重新登录');
        } else if (error?.response?.status === 403) {
          throw new Error('没有权限访问菜单数据');
        } else if (error?.response?.status >= 500) {
          throw new Error('服务器错误，请稍后重试');
        } else if (error?.code === 'NETWORK_ERROR') {
          throw new Error('网络连接失败，请检查网络');
        } else {
          throw new Error(error?.message || '获取菜单列表失败');
        }
      }
    });
  }, [executeAsync]);

  // 创建菜单
  const createMenu = useCallback(async (data: CreateMenuRequest) => {
    return executeAsync('createMenu', async () => {
      try {
        await menuApi.createMenu(data);
        message.success('菜单创建成功');
        // 重新加载数据，使用当前的搜索参数
        setSearchParams(prev => {
          fetchMenus(prev);
          return prev;
        });
      } catch (error: any) {
        if (error?.response?.status === 409) {
          throw new Error('菜单编码已存在，请使用其他编码');
        } else if (error?.response?.data?.message) {
          throw new Error(error.response.data.message);
        } else {
          throw new Error('菜单创建失败');
        }
      }
    });
  }, [executeAsync, fetchMenus]);

  // 更新菜单
  const updateMenu = useCallback(async (data: UpdateMenuRequest) => {
    return executeAsync('updateMenu', async () => {
      try {
        await menuApi.updateMenu(data);
        message.success('菜单更新成功');
        // 重新加载数据，使用当前的搜索参数
        setSearchParams(prev => {
          fetchMenus(prev);
          return prev;
        });
      } catch (error: any) {
        if (error?.response?.status === 409) {
          throw new Error('菜单编码已存在，请使用其他编码');
        } else if (error?.response?.data?.message) {
          throw new Error(error.response.data.message);
        } else {
          throw new Error('菜单更新失败');
        }
      }
    });
  }, [executeAsync, fetchMenus]);

  // 删除菜单
  const deleteMenu = useCallback(async (id: string) => {
    return executeAsync('deleteMenu', async () => {
      try {
        await menuApi.deleteMenu(id);
        message.success('菜单删除成功');
        // 重新加载数据，使用当前的搜索参数
        setSearchParams(prev => {
          fetchMenus(prev);
          return prev;
        });
      } catch (error: any) {
        if (error?.response?.data?.message) {
          throw new Error(error.response.data.message);
        } else {
          throw new Error('菜单删除失败');
        }
      }
    });
  }, [executeAsync, fetchMenus]);

  // 批量删除菜单
  const deleteMenus = useCallback(async (ids: string[]) => {
    return executeAsync('deleteMenus', async () => {
      try {
        await Promise.all(ids.map(id => menuApi.deleteMenu(id)));
        message.success(`成功删除 ${ids.length} 个菜单`);
        // 重新加载数据，使用当前的搜索参数
        setSearchParams(prev => {
          fetchMenus(prev);
          return prev;
        });
      } catch (error: any) {
        if (error?.response?.data?.message) {
          throw new Error(error.response.data.message);
        } else {
          throw new Error('批量删除菜单失败');
        }
      }
    });
  }, [executeAsync, fetchMenus]);

  // 搜索处理
  const handleSearch = useCallback((keyword: string) => {
    setSearchParams(prev => {
      const params = {
        ...prev,
        keyword: keyword || undefined
      };
      fetchMenus(params);
      return params;
    });
  }, [fetchMenus]);

  // 重置搜索
  const handleReset = useCallback(() => {
    setSearchParams({});
    fetchMenus();
  }, [fetchMenus]);

  // 处理筛选条件变化
  const handleFilterChange = useCallback((key: string, value: any) => {
    setSearchParams(prev => {
      const params = {
        ...prev,
        [key]: value || undefined
      };
      fetchMenus(params);
      return params;
    });
  }, [fetchMenus]);

  // 刷新数据
  const refresh = useCallback(() => {
    setSearchParams(prev => {
      fetchMenus(prev);
      return prev;
    });
  }, [fetchMenus]);

  return {
    // 数据状态
    menus,
    menuTree,
    searchParams,
    expandedKeys,
    setExpandedKeys,
    
    // 加载状态
    loading: hasAnyLoading,
    
    // 操作方法
    fetchMenus,
    createMenu,
    updateMenu,
    deleteMenu,
    deleteMenus,
    handleSearch,
    handleReset,
    handleFilterChange,
    refresh,
  };
};

import { FolderOutlined, FileOutlined, ApiOutlined } from '@ant-design/icons';
import React from 'react';

/**
 * 菜单类型选项hooks
 */
export const useMenuTypeOptions = () => {
  const MENU_TYPE_OPTIONS = [
    { label: '目录', value: 1, icon: React.createElement(FolderOutlined) },
    { label: '菜单', value: 2, icon: React.createElement(FileOutlined) },
    { label: '按钮', value: 3, icon: React.createElement(ApiOutlined) }
  ];

  const STATUS_OPTIONS = [
    { label: '启用', value: 1, color: 'success' },
    { label: '禁用', value: 0, color: 'error' }
  ];

  return {
    MENU_TYPE_OPTIONS,
    STATUS_OPTIONS,
  };
};